﻿using UnityEngine;
using System.Collections;

public class MenuManager : MonoBehaviour 
{
	public Texture texture;
	
	private User user;
	private FacebookController facebookController;

	//public delegate void UpdateDelegate();
	//public event UpdateDelegate UpdateInyection = delegate {};

	private Match currentMatch;
	
	private GUIState prevState;
	private GUIState state;
	private enum GUIState
	{
		Loading,
		Facebook,
		Normal,
		CurrentMatches,
		Options
	}

	private ShowMatchState showState;
	private enum ShowMatchState
	{
		Simple,
		Detail
	}
		
	private string soundButtonLabel;
	
	private void Awake()
	{
		showState = ShowMatchState.Simple;

		string userName = PlayerPrefs.GetString("UserName");
		string facebookID = PlayerPrefs.GetString("FacebookID");

		SoundSystem.isMute = ((PlayerPrefs.GetInt ("Sound") == Constants.SOUND_DISABLED) ? true : false);
		soundButtonLabel = SoundSystem.isMute ? Constants.OPTIONS_SOUND_ENABLE : Constants.OPTIONS_SOUND_DISABLE;

		user = User.Instance;

		if (string.IsNullOrEmpty(facebookID)) 
		{
			user.SetUserNormal(userName);
			state = GUIState.Normal;
			prevState = GUIState.Normal;
		}
		else
		{
			user.SetUserFacebook(userName, facebookID);
			prevState = GUIState.Facebook;
			state = GUIState.Loading;
			
			facebookController = new FacebookController();
			
			facebookController.CleanGraphActions ();
			facebookController.graphRequestCompletedEvent += GetMeCallbackSuccess;
			facebookController.graphRequestFailedEvent += GraphRequestedFailed;

			facebookController.GetMe ();
		}
	}
	
	private void FacebookState()
	{				
		if (GUILayout.Button("Partida Automatica"))
		{
			PlayerPrefs.SetInt("MatchType", Constants.MATCH_TYPE_DECK);
			Application.LoadLevel(Constants.SCENE_INGAME);
		}

		if (GUILayout.Button("Crear Partida Rapida"))
		{
			PlayerPrefs.SetInt("MatchType", Constants.MATCH_TYPE_DECKPLUS);
			Application.LoadLevel(Constants.SCENE_INGAME);
		}

		if (GUILayout.Button("Crear Partida Completa"))
		{
			PlayerPrefs.SetInt("MatchType", Constants.MATCH_TYPE_QUESTIONS);
			Application.LoadLevel(Constants.SCENE_INGAME);
		}
		
		if (GUILayout.Button("Partidas en Curso"))
		{
			state = GUIState.CurrentMatches;
		}	
		
		if (GUILayout.Button("Options"))
		{
			state = GUIState.Options;
		}
		if (GUILayout.Button("Log Out"))
		{
			//callbackslocos
			FacebookLogOut ();
			Application.LoadLevel(Constants.SCENE_LOGIN);
		}	
	}

	private void NormalState()
	{		
		// Avisar que si se logea con facebook tiene mas modalidades

		if (GUILayout.Button("Partida Automatica"))
		{
			PlayerPrefs.SetInt("MatchType", Constants.MATCH_TYPE_DECK);
			Application.LoadLevel(Constants.SCENE_INGAME);
		}

		// ELIMINAR ESTAS DOS......
		if (GUILayout.Button("Crear Partida Rapida"))
		{
			PlayerPrefs.SetInt("MatchType", Constants.MATCH_TYPE_DECKPLUS);
			Application.LoadLevel(Constants.SCENE_INGAME);
		}
		
		if (GUILayout.Button("Crear Partida Completa"))
		{
			PlayerPrefs.SetInt("MatchType", Constants.MATCH_TYPE_QUESTIONS);
			Application.LoadLevel(Constants.SCENE_INGAME);
		}
		
		if (GUILayout.Button("Partidas en Curso"))
		{
			state = GUIState.CurrentMatches;
		}	
		
		if (GUILayout.Button("Options"))
		{
			state = GUIState.Options;
		}

		if (GUILayout.Button("Log in with Facebook"))
		{
			//callbackslocos
			Application.LoadLevel(Constants.SCENE_LOGIN);
		}	
	}

	private void OptionsState()
	{				
		if (GUILayout.Button(soundButtonLabel))
		{
			SoundSystem.isMute = !SoundSystem.isMute;
			PlayerPrefs.SetInt("Sound", SoundSystem.isMute ? Constants.SOUND_DISABLED : Constants.SOUND_ENABLED);
			soundButtonLabel = SoundSystem.isMute ? Constants.OPTIONS_SOUND_ENABLE : Constants.OPTIONS_SOUND_DISABLE;
		}

		if (GUILayout.Button("Contact"))
		{
			//email
		}
		
		GUILayout.TextField("Credits: NEGRO Y GORDO EN EL NORTE");

		if (GUILayout.Button("Back"))
		{
			state = prevState;
		}
	}

	private void CurrentMatchesState()
	{
		if (GUILayout.Button("Options"))
		{
			state = GUIState.Options;
		}

		if (showState == ShowMatchState.Simple)
		{
			ShowMatchesList();
		}
		else if (showState == ShowMatchState.Detail)
		{
			ShowMatchesDetail(currentMatch);
		}
	}

	private void ShowMatchesList()
	{
		if (GUILayout.Button("Back"))
		{
			state = prevState;
		}

		if (user != null && user.Matches.Count > 0)
		{
			foreach (Match m in user.Matches)
			{
				if (GUILayout.Button ("Partida " + m.Name))
				{
					showState = ShowMatchState.Detail;
					
					currentMatch = m;
				}
			}
		}
	}
	
	private void ShowMatchesDetail(Match match)
	{
		if (GUILayout.Button("Back"))
		{
			showState = ShowMatchState.Simple;
		}

		for (int i = 0; i < match.Players.Count; ++i)
		{
			GUILayout.TextField ("Jugador " + i + ":" + match.Players[i].Nick);
		}
		
		GUILayout.TextField ("Pregunta: " + match.Question);
		
		for (int i = 0; i < match.Answers.Count; ++i)
		{
			GUILayout.TextField ("Respuesta " + i + ":" + match.Answers[i]);
		}
		
		GUILayout.TextField ("Respuesta Elegida: " + match.SelectedAnswer);
	}
	
	private void LoadingState()
	{
		GUILayout.TextField("Cargando. Por favor Espere...");
	}

	private void OnGUI()
	{		
		GUI.DrawTexture(new Rect(0f, 0f, Screen.width, Screen.height), texture);
		
		switch (state)
		{
			case GUIState.Facebook:
			{
				FacebookState();
				break;
			}
				
			case GUIState.Normal:
			{
				NormalState();
				break;
			}
				
			case GUIState.CurrentMatches:
			{
				CurrentMatchesState();
				break;
			}
				
			case GUIState.Options:
			{
				OptionsState();
				break;
			}

			case GUIState.Loading:
			{
				LoadingState();
				break;
			}

			default:
			{
				NormalState();
				break;
			}
		}
	}

	#region GetUserInfo
	public void GetMeCallbackSuccess()
	{
		Debug.Log("GetMeCallbackSuccess");	
		
		#if UNITY_IPHONE || UNITY_ANDROID
		facebookController.graphRequestCompletedEvent -= GetMeCallbackSuccess;
		#endif
		
		FacebookUserConnected();		
	}	
	
	private void FacebookUserConnected()
	{				
		#if UNITY_IPHONE || UNITY_ANDROID
		//GenericPopup.Instance.ShowPopupOk("FacebookUserCheck", ()=>{}, false,true);
		facebookController.graphRequestCompletedEvent += GetFriendsCallbackSuccess;
		facebookController.GetFacebookFriends ();
		#endif
	}
	
	public void GetFriendsCallbackSuccess()
	{
		#if UNITY_IPHONE || UNITY_ANDROID
		Debug.Log("GetFriendsCallbackSuccess");	
		if (facebookController.GetFriendsCount () <= 0)
		{
			#if UNITY_IPHONE || UNITY_ANDROID
			facebookController.InvitePlayer ();
			#endif
		}		
		state = prevState;
		#endif
	}

	public void GraphRequestedFailed()
	{
		Debug.Log("GraphRequestedFailed");	
		state = prevState;
	}
	#endregion
	public void FacebookLogOut()
	{
		#if UNITY_IPHONE || UNITY_ANDROID
		if (Application.internetReachability != NetworkReachability.NotReachable)
		{
			if (facebookController.IsLogged())
			{
				facebookController.LogOut ();
			}
		}
		#endif
	}
}
